<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>在线聊天室</title>
    <!--vue-->
    <script src="https://cdn.staticfile.org/vue/2.7.0/vue.min.js"></script>
    <!-- 引入样式 -->
    <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
    <!-- 引入组件库 -->
    <script src="https://unpkg.com/element-ui/lib/index.js"></script>
    <script src="./js/vue.js"></script>
  <script src="./js/element.js"></script>
  <script src="./js/axios.min.js"></script>

    <style>
        .tip {
            color: white;
            text-align: center;
            border-radius: 10px;
            font-family: sans-serif;
            padding: 10px;
            width:auto;
            display:inline-block !important;
            display:inline;
        }

        .right {
            background-color: deepskyblue;
        }
        .left {
            background-color: forestgreen;
        }
    </style>

</head>
<body style="margin:0">
<!-- <script src="./js/request.js"></script> -->
<div id="root" >
    <div style="">
        <el-row style="display:flex">
            <el-col :span="8" style="width:30% ;height:660px;">
                <el-card style="color: #333;overflow:auto;height:1000px;">
                    <div style="padding-bottom: 10px; border-bottom: 1px solid #ccc;font-size:24px;">用户列表</div><span style="font-size: 10px color:Chocolate ">（点击用户开始聊天）</span>
                     	<h3 >在线用户</h3>
					 <div style=" padding: 10px 0;font-size:30px;line-height:10px" v-for="(online,index) in onlineUsers" :key="index">
					 <span  @click="chatUser = online.username;chatUserIcon='';content =''">
				       {{online.username}} 	 <div style="background-color:green;height: 15px; width: 15px; line-height: 10px;border-radius:50%;float: left"></div>
                        <i  class="el-icon-chat-dot-round" style="margin-left: 10px; font-size: 20px; cursor: pointer"  ></i>
                         
						     <span style="font-size: 20px;color: limegreen; " v-if="online.username ===chatUser">聊天中..</span>
						
						    </span>
            
                    </div>
					<hr>
					<h3>登录用户</h3>
						  <div>
					   <div style="float: left"><img :src="loginIcon || morenIcon" style="height: 100px; width: 100px; line-height: 70px;border-radius:50%;overflow:hidden;float: right"></img> 
					  
                            
					  </div>  <div style="background-color:green;height: 26px; width: 26px; line-height: 10px;border-radius:50%;float: left" ></div> 
					   <span style="font-size:25px">  {{loginName }}</span>
					 
					 
				     
					 </div><br><br><br><br>
					   <h2 @click="chatUser='聊天小群';content =''">聊天小群</h2>
					<hr>
					<h3>所有用户</h3>(上滑查看更多,点击头像查看用户)
					<div style=" padding: 10px 0;font-size:20px;line-height:10px" v-for="(user,index) in users" :key="user.nickName">
				
					  <br><br>
					
					  <div>
                      <img :src="user.icon || '/imgs/icons/default-icon.png'" style="height: 80px; width: 80px; line-height: 10px;border-radius:50%;overflow:hidden"  @click="toOtherInfo(user) "></img>  
					  <span @click="chatUser = user.nickName;chatUserIcon=user.icon||morenIcon;content =''">
					   
						   <span style="color:green;font-weight: bold;font-size:30px" v-if="user.nickName ===chatUser">
						  <i class="el-icon-chat-dot-round" style="margin-left: 10px; font-size: 32px; cursor: pointer;color:green">  </i>
					      {{ user.nickName }}
					    </span>
						<span v-else>
						 <i class="el-icon-chat-dot-round" style="margin-left: 10px; font-size: 23px; cursor: pointer;">  </i>
						{{ user.nickName }}
						</span>
						  
                      
                        <!-- <span style="font-size: 20px;color: limegreen; margin-left: 5px" v-if="user.nickName ===chatUser">被选中</span> -->
						</div>
                    </div>
                </el-card>
            </el-col>

            <el-col :span="8" style="width:70% ">
                <div style=" margin: 0 auto; background-color: white; margin-left: auto;
                    border-radius: 5px; box-shadow: 0 0 10px #ccc;">
                    <div style="text-align: center; line-height: 60px; font-size:35px;" >
                       <div  @click="goBack" style="float: left;color:teal"><i class="el-icon-arrow-left"></i>退出</div>
					   <img :src="(chatUserIcon|| morenIcon)" style="height:  70px; width:  70px; line-height:70px;border-radius:50%;overflow:hidden"/>
					 <span style="color:black"> {{ this.chatUser==''?"未选择聊天用户":this.chatUser}}</span>

                    </div>
                    <div ref="scrollDiv" style=" overflow-y:auto;overflow-x:0; height:900px;border-top: 1px solid #ccc" v-html="content"></div>
                    <div style="">
            <textarea v-model="text" placeholder="说点什么呢" style="height: 160px; width: 94%; padding: 20px; border: none; border-top: 1px solid #ccc;
             border-bottom: 1px solid #ccc; outline: non;font-size:18px"></textarea>
                        <div style="text-align: right; padding-right: 10px" >
                            <el-button type="primary" size="large" @click="send">发送</el-button>
                        </div>
                    </div>
                </div>
            </el-col>
        </el-row>
    </div>

</div>
<script src="./js/vue.js"></script>
<script src="./js/axios.min.js"></script>
<!-- 引入组件库 -->
<script src="./js/element.js"></script>
<script src="./js/common.js"></script>
<script src="./js/footer.js"></script>
<script type="text/javascript">

    let socket;
	let name;
    const vm = new Vue({
        el: '#root',

        data: {
            circleUrl: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
            user: {
			  nickName:'',
			  id:''
			
			},
            isCollapse: false,
            chatUser: '',
			morenIcon:'/imgs/icons/default-icon.png',//默认头像
			chatUserIcon:'',//聊天用户头像
            text: "",
			loginName:'',//登录的用户名
            messages: [],
            content: '',
			util,
			onlineUsers:[],//在线用户
			loginIcon:'',//登录用户头像
            users: [],
        },
        created() {
		this.queryAllUsers();
            this.init();
        },
		//监听内容变化
	 watch: {
        content(newVal,oldVal){
          //  console.log('content的值发生了变化')
            //console.log(newVal,oldVal)
			 this.change();
        }
    },
  methods: {
       //滚动到消息底部
		 change(){
			    setTimeout(()=>{
            var div=this.$refs.scrollDiv;
                    div.scrollTop = div.scrollHeight;
                },0)
		 },
		 //通知某人
      informTo() {
        this.$notify.success({
          title: 'Info',
          message: '有人想和你聊天了，点击它和他聊天',
          showClose: false
        });
      },
		   goBack() {
        history.back();
      },
		
			//查询登录用户
	 checkLogin() {
	   // 查询用户信息
         name = util.getUrlParam("name");
		 icon = util.getUrlParam("icon");
		 
		this.loginName=name;
		this.loginIcon=icon;
		this.user.nickName=name;
		console.log("名："+this.user.nickName)
		console.log("图："+this.loginIcon)
        // 查询用户信息
        <!-- axios.get(" http://localhost:8081/user/me") -->
        <!-- .then(({data}) => { -->
		
	
          <!-- this.user = data; -->
		  <!-- console.log("查到登录用户名为:"+this.user.nickName); -->
        <!-- }) -->
		
	},
	 	//查看用户
	    toOtherInfo(user){
          location.href = "/other-info.html?id=" + user.id
        
      },
	 

	//查询所有用户
	queryAllUsers(){
	
	 axios.get("http://localhost:8081/user/list")
	  .then(({data})=>{
	   this.users=data;
	   
	  })
	
	
	},
            send() {
                if (!this.chatUser) {
                    this.$message({type: 'warning', message: "请选择聊天对象"})
                   return;
                }
                if (!this.text) {    
                    this.$message({type: 'warning', message: "请输入内容"})
                } else {
                    if (typeof (WebSocket) == "undefined") {
                        console.log("您的浏览器不支持WebSocket");
                    } else {
                        console.log("您的浏览器支持WebSocket");
                        // 组装待发送的消息 json
                        // {"from": "zhang", "to": "admin", "text": "聊天文本"}
                        let message = {from: this.user.nickName, to: this.chatUser, text: this.text}
					
                        socket.send(JSON.stringify(message));  // 将组装好的json发送给服务端，由服务端进行转发
                        this.messages.push({user: this.user.nickName, text: this.text})
                        // 构建消息内容，本人消息
                        this.createContent(null, this.user.nickName, this.text)
						
                        this.text = '';
						
						
                    }

                }
            },

            createContent(remoteUser, nowUser, text) {  // 这个方法是用来将 json的聊天消息数据转换成 html的。
			
			console.log("接受人:"+this.chatUser+" 发送人:"+nowUser+" 内容是:"+text)
				if( this.chatUser===this.loginName){//登录用户和被接受聊天信息用户一致时，通知该用户 -->
								console.log("进来了")

								 
								}
			
                let html
                // 当前用户消息
                if (nowUser) { // nowUser 表示是否显示当前用户发送的聊天消息，绿色气泡
                    html = "<div  class=\"el-row\" style=\"padding: 5px 0;\">\n" +
                        "  <div class=\"el-col el-col-22\" style=\"text-align: right; padding-right: 10px;font-size:30px; padding-top: 10px; padding-bottom: 10px;\">\n" +
                        "    <div class=\"tip left\">" + text + "</div>\n" +
                        "  </div>\n" +
                        "  <div class=\"el-col el-col-2\">\n" +
                        "  <span class=\"el-avatar el-avatar--circle\" style=\"height: 70px; width: 70px; line-height: 70px;\">\n" +
                        "    <img src=\"."+(this.loginIcon||this.morenIcon)+"\" style=\"object-fit: cover;\">\n" +
                        "  </span>\n" +
                        "  </div>\n" +
                        "</div>";
                } else if (remoteUser) {   // remoteUser表示远程用户聊天消息，蓝色的气泡
                    html = "<div  class=\"el-row\" style=\"padding: 5px 0\">\n" +
                        "  <div class=\"el-col el-col-2\" style=\"text-align: right\">\n" +
                        "  <span class=\"el-avatar el-avatar--circle\" style=\"height: 70px; width: 70px; line-height: 70px;\">\n" +
                        "    <img src=\"."+(this.chatUserIcon||this.morenIcon)+"\" style=\"object-fit: cover;\">\n" +
                        "  </span>\n" +
                        "  </div>\n" +
                        "  <div class=\"el-col el-col-22\" style=\"text-align: left; padding-left: 10px;font-size:30px;padding-top: 10px; padding-bottom: 10px;\">\n" +
                        "    <div class=\"tip right\">" + text + "</div>\n" +
                        "  </div>\n" +
                        "</div>";
                }
                console.log(html)
                this.content += html;
				
            },
            init() {
               this.checkLogin();//查询登录用户
                let username = this.loginName;
                let _this = this;
                if (typeof (WebSocket) == "undefined") {
                    console.log("您的浏览器不支持WebSocket");
                } else {
                    console.log("您的浏览器支持WebSocket");
                    let socketUrl = "ws://localhost:8081/ws/" + username;
					
                    if (socket != null) {
                        socket.close();
                        socket = null;
                    }
                    // 开启一个websocket服务
                    socket = new WebSocket(socketUrl);
                    //打开事件
                    socket.onopen = function () {
                        console.log("websocket已打开");
                    };
                    //  浏览器端收消息，获得从服务端发送过来的文本消息
                    socket.onmessage = function (msg) {
                        console.log("收到数据====" + msg.data)
                        let data = JSON.parse(msg.data)  // 对收到的json数据进行解析， 类似这样的： {"users": [{"username": "zhang"},{ "username": "admin"}]}
                        if (data.users) {  // 获取在线人员信息
                          //  _this.users = data.users.filter(user => user.nickName !== username)  // 获取当前连接的所有用户信息，并且排除自身，自己不会出现在自己的聊天列表里
								_this.onlineUsers=data.users;
							//	alert("data---"+data.users[0].username);
                        } else {
                            // 如果服务器端发送过来的json数据 不包含 users 这个key，那么发送过来的就是聊天文本json数据
                            //  // {"from": "zhang", "text": "hello"}
								console.log("-----聊天去")
						
                            if (data.from === _this.chatUser) {
                                _this.messages.push(data)
                                // 构建消息内容
                                _this.createContent(data.from, null, data.text)
								
                            }else{
							alert('用户:'+data.from+" 给你发了:"+data.text);
							}
                        }
                    };
                    //关闭事件
                    socket.onclose = function () {
                        console.log("websocket已关闭");
                    };
                    //发生了错误事件
                    socket.onerror = function () {
                        console.log("websocket发生了错误");
                    }
                }
            }

        }


    });
    console.log(vm)

</script>



</body>
</html>